import { useState, useEffect } from 'react'
import HeaderList from "../components/HeaderList"
import Discuss from "../components/Disscuss"
import { Image, message, Modal } from 'antd';
import { useParams } from "react-router-dom"
import { useSelector, useDispatch } from "react-redux"
import { updateUserInfo } from "../redux/userSlice"
import styles from "../css/BookDetail.module.scss"
import { getBookById, updateBookInfo } from "../api/book"
import { IStore } from '../redux/typings';
import { IBookInfo } from "../typings/index"
import { updateUserById } from "../api/user"

function BookDetail() {
    const { id } = useParams();
    const [bookInfo, setBookInfo] = useState<IBookInfo>();
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 获取用户信息
    const { userInfo, isLogin } = useSelector((state: IStore) => state.user);
    const dispatch = useDispatch();

    useEffect(() => {
        const fetchData = async () => {
            try {
                // @ts-ignore
                const { data } = await getBookById(id);
                setBookInfo(data.data)
                // @ts-ignore 书籍浏览数+1
                updateBookInfo(id, ++data.data.scanNumber)
            } catch (e) {
                console.log("获取书籍详细信息失败", e)
            }
        }
        fetchData()
    }, [])

    const showModal = () => {
        setIsModalOpen(true);
    }
    const handleOk = () => {
        // 确定下载
        // 需要判断积分是否足够
        if ((userInfo.points as number) - (bookInfo as IBookInfo).requirePoints < 0) {
            message.warning("积分不足");
        } else {
            // 积分是够的 
            // 服务器扣积分
            // @ts-ignore
            updateUserById(userInfo._id, {
                points: (userInfo.points as number) - (bookInfo as IBookInfo).requirePoints
            });
            // 本地仓库也需要更新
            dispatch(updateUserInfo({
                points: (userInfo.points as number) - (bookInfo as IBookInfo).requirePoints
            }))
            window.open(`${(bookInfo as IBookInfo).downloadLink}`);
            message.success("积分已扣除");
        }
        setIsModalOpen(false);
    }

    const handleCancel = () => {
        setIsModalOpen(false)
    }
    return (
        <div>
            <HeaderList title="书籍详情" />
            <div className={styles.bookInfoContainer}>
                <div className={styles.leftSide}>
                    <div className={styles.img}>
                        <Image
                            height={350}
                            src={bookInfo?.bookPic}
                        />
                    </div>
                    <div className={styles.link}>
                        <span>下载所需积分: <span className={styles.requirePoints}>{bookInfo?.requirePoints}</span> 分</span>
                        {
                            isLogin ? (
                                <div className={styles.downloadLink} onClick={showModal}>
                                    百度云下载地址
                                </div>
                            ) : null
                        }

                    </div>
                </div>
                <div className={styles.rightSide}>
                    <h1 className={styles.title}>{bookInfo?.bookTitle}</h1>
                    <div dangerouslySetInnerHTML={{ __html: bookInfo?.bookIntro as string }}></div>
                </div>
            </div>
            <div className={styles.comment}>
                <Discuss
                    bookInfo={bookInfo}
                    commentType={2}
                    targetId={bookInfo?._id}
                />
            </div>
            <Modal title="重要提示" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <p>是否使用 <span className={styles.requirePoints}>{bookInfo?.requirePoints}</span> 积分下载此书籍？</p>
            </Modal>
        </div>
    )
}

export default BookDetail
